#pragma once

#include <unistd.h>
#include <sys/epoll.h>
#include "Log.hpp"
#include "nocopy.hpp"

class Epoller : public nocopy
{
public:
    Epoller()
    {
        _epfd = epoll_create1(0);
        if(_epfd == -1)
            log(Error, "epoll_create error: %s", strerror(errno));
        else
            log(Info, "epoll_create success: %d", _epfd);
    }

    int EpollWait(struct epoll_event revs[], int num)
    {
        int n = epoll_wait(_epfd, revs, num, _timeout);
        return n;
    }

    int EpollCtl(int op, int fd, uint32_t event)
    {
        int n = 0;
        if(op == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, op, fd, nullptr);
            if(n != 0)
                log(Error, "epoll_ctl delete error!");
        }
        else
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = fd;

            epoll_ctl(_epfd, op, fd, &ev);
            if (n != 0)
            {
                log(Error, "epoll_ctl error!");
            }
        }
        return n;
    }

    ~Epoller()
    {
        if(_epfd > 0)
            close(_epfd);
    }

private:
    int _epfd;
    int _timeout{3000};
};